#!/bin/bash

# MessageFramework测试运行脚本

set -e  # 遇到错误立即退出

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

echo -e "${GREEN}========================================${NC}"
echo -e "${GREEN}MessageFramework测试套件${NC}"
echo -e "${GREEN}========================================${NC}"
echo ""

# 检查构建目录
if [ ! -d "../build" ]; then
    echo -e "${RED}错误: 未找到build目录${NC}"
    echo "请先运行: cd .. && mkdir build && cd build && cmake .. && make"
    exit 1
fi

cd ../build

# 检查Redis连接
echo -e "${YELLOW}检查Redis连接...${NC}"
if ! redis-cli -a "redis_EX7Nms" ping > /dev/null 2>&1; then
    echo -e "${RED}错误: 无法连接到Redis${NC}"
    echo "请确保Redis服务正在运行：redis-server"
    exit 1
fi
echo -e "${GREEN}✓ Redis连接正常${NC}"
echo ""

# 运行单元测试
echo -e "${YELLOW}========================================${NC}"
echo -e "${YELLOW}运行单元测试...${NC}"
echo -e "${YELLOW}========================================${NC}"

UNIT_TESTS=(
    "test_message_header"
    "test_signature_helper"
    "test_encryption_helper"
    "test_message_dispatcher"
    "test_message_producer"
    "test_message_consumer"
)

UNIT_PASSED=0
UNIT_FAILED=0

for test in "${UNIT_TESTS[@]}"; do
    echo -e "\n${YELLOW}运行: $test${NC}"
    if ./$test; then
        echo -e "${GREEN}✓ $test 通过${NC}"
        ((UNIT_PASSED++))
    else
        echo -e "${RED}✗ $test 失败${NC}"
        ((UNIT_FAILED++))
    fi
done

echo ""
echo -e "${YELLOW}单元测试结果: ${GREEN}${UNIT_PASSED} 通过${NC}, ${RED}${UNIT_FAILED} 失败${NC}"
echo ""

# 运行集成测试
echo -e "${YELLOW}========================================${NC}"
echo -e "${YELLOW}运行集成测试...${NC}"
echo -e "${YELLOW}========================================${NC}"

INTEGRATION_TESTS=(
    "test_e2e"
    "test_fault_tolerance"
)

INTEGRATION_PASSED=0
INTEGRATION_FAILED=0

for test in "${INTEGRATION_TESTS[@]}"; do
    echo -e "\n${YELLOW}运行: $test${NC}"
    if ./$test; then
        echo -e "${GREEN}✓ $test 通过${NC}"
        ((INTEGRATION_PASSED++))
    else
        echo -e "${RED}✗ $test 失败${NC}"
        ((INTEGRATION_FAILED++))
    fi
done

echo ""
echo -e "${YELLOW}集成测试结果: ${GREEN}${INTEGRATION_PASSED} 通过${NC}, ${RED}${INTEGRATION_FAILED} 失败${NC}"
echo ""

# 总结
TOTAL_PASSED=$((UNIT_PASSED + INTEGRATION_PASSED))
TOTAL_FAILED=$((UNIT_FAILED + INTEGRATION_FAILED))
TOTAL_TESTS=$((TOTAL_PASSED + TOTAL_FAILED))

echo -e "${GREEN}========================================${NC}"
echo -e "${GREEN}测试总结${NC}"
echo -e "${GREEN}========================================${NC}"
echo -e "总测试数: $TOTAL_TESTS"
echo -e "${GREEN}通过: $TOTAL_PASSED${NC}"
echo -e "${RED}失败: $TOTAL_FAILED${NC}"
echo ""

if [ $TOTAL_FAILED -eq 0 ]; then
    echo -e "${GREEN}✓ 所有测试通过！${NC}"
    exit 0
else
    echo -e "${RED}✗ 有 $TOTAL_FAILED 个测试失败${NC}"
    exit 1
fi
